package game.units;

import java.awt.Point;
import java.util.Iterator;
import java.util.Vector;

import utils.GameMaths;
import core.rendering.Renderable;

public abstract class UnitPool extends Renderable {

	private Vector<Unit> units;
	public UnitPool(int size , Point begin , Point end) {
		units = new Vector<Unit>();
		
		for (int cont = 0; cont < size; cont++) {
			SimpleUnit u = new SimpleUnit(begin, end);
			this.addUnit(u);
		}
	}

	/**
	 * Returns the closest element in the pool to the other parameter unit.
	 * 
	 * @param other
	 * @return
	 */
	public Unit getClosest(Unit other) {
		Unit ret = null;
		Iterator<Unit> it = units.iterator();
		while (it.hasNext()) {
			Unit now = it.next();
			float min_dist = 0.0f;
			float current_dist = 0.0f;
			if (ret == null) {
				ret = now;
			} else {
				min_dist = GameMaths.distance(now.getX(), now.getY(), other
						.getX(), other.getY());
				current_dist = GameMaths.distance(ret.getX(), ret.getY(), other
						.getX(), other.getY());
			}
			if (min_dist < current_dist) {
				ret = now;
			}
		}
		return ret;
	}

	/**
	 * Adds a new unit to the pool.
	 * 
	 * @param u
	 */
	public void addUnit(Unit u) {
		units.add(u);
	}

	public void remove(Unit u) {
		units.remove(u);
	}

	public Iterator<Unit> iterator() {
		return units.iterator();
	}

	public Vector<Unit> getUnits(){
		return units;
	}
	
	
	public boolean isEmpty() {
		return units.isEmpty();
	}

	public boolean contains(Unit u) {
		return units.contains(u);
	}

	public Vector<Unit> getDeathUnits() {
		Vector<Unit> ret = new Vector();
		Iterator<Unit> it = units.iterator();
		while (it.hasNext()) {
			Unit u = it.next();
			// DBG.showMsg(u.getHealth() + " hp ", this);
			if (u.getHealth() <= 0) {
				ret.add(u);
			}
		}
		return ret;
	}
}
